from django.contrib.auth.models import User
from django.http import HttpResponse
from django.shortcuts import render,redirect
from django.contrib.auth import authenticate, login,logout
from django.contrib import auth

# session
def getsessionfun(request):
    print(request.session['sname'] )
    print(request.session['spwd'] )
    return render(request,'sessionvalue.html')


def setsessionfun(request):
    request.session['sname']='laoyang'
    request.session['spwd']='123'
    return render(request,'sessionvalue.html')


def delsessionfun(request):
    del request.session['spwd']
    print(request.session['sname'])
    request.session.flush()
    # print(request.session['spwd'])
    return render(request,'sessionvalue.html')



# 设置 cookie:
# rep =HttpResponse || render || redirect
# rep.set_cookie(key,value,...)
# rep.set_signed_cookie(key,value,salt='加密盐',...)

def setcookiefun(request):
    rep = HttpResponse(" cookie OK")
    rep.set_cookie('name', 'yangtao')
    return rep


# 删除 cookie:
#
# rep.delete_cookie(key)


def delcookiefun(request):
    rep = HttpResponse('del cookie')#|| render | | redirect
    rep.delete_cookie('name')
    return rep


#
# 获取 cookie:
#
# request.COOKIES.get(key)
#
def getcookiefun(request):
    name=request.COOKIES.get('name')
    return HttpResponse(name)

# 创建用户对象的三种方法：
#
#     create()：创建一个普通用户，密码是明文的。
#     create_user()：创建一个普通用户，密码是密文的。
#     create_superuser()：创建一个超级用户，密码是密文的，要多传一个邮箱 email 参数。

def createUser(request):
    # 添加用户，第一次正确，第二次失败，因为用户已经存在
    try:
        User.objects.create(username='yangtao',password='123')
    except Exception as e:
        print(e)
        return HttpResponse('用户已存在')
    return HttpResponse("create user (yangtao,123) ok")


def createUser2(request):
    # 添加用户，第一次正确，第二次失败，因为用户已经存在
    try:
        #密码不使用明文
        User.objects.create_user(username='laoyang',password='123')
    except Exception as e:
        print(e)
        return HttpResponse('用户已存在')
    return HttpResponse("create user (laoyang,123) ok")

# 经过几次登录操作，发现，明文的密码无法登录
# 需要加密后的密码登录才行
# Django自带的用户认证 感觉上，还是比较成熟，反正大多数软件都需要登录，用上方便不少
def userlogin(request):
    if request.method == "GET":
        return render(request, "userlogin.html")
    username = request.POST.get("username")
    password = request.POST.get("pwd")
    #因为没有做验证码，就去掉了
    valid_num ='1'# request.POST.get("valid_num")
    keep_str ='1' # request.session.get("keep_str")
    if keep_str.upper() == valid_num.upper():
        user_obj = authenticate(request,username=username, password=password)
        # print(user_obj.username)
        if not user_obj:
            print('登录失败')
            return redirect("/userlogin/")
        else:
            login(request, user_obj)
            print('登录成功')
            return HttpResponse('登录成功')
    else:
        return redirect("/userlogin/")

def logout(request):
    ppp = logout(request)
    print(ppp)  # None
    return redirect("/userlogin/")